package cn.org.zx.common.file;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.*;
import jxl.read.biff.BiffException;

import javax.servlet.http.HttpServletRequest;
import cn.org.zx.common.commutils.CommMethod;

public class ImportControler{	
	public Map getImportMsg_drmanage(HttpServletRequest request,String strExcelName) throws ImpException{
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			throw new ImpException("UnsupportedEncodingException------ImportControler.getImportMsg_drmanage();ic00");
		}
		
		Map hashReturn = new HashMap();
		List lReadExcel = null;				
		int iFromRowNum = 2;	//起始行
		
		try {	
			//读文件	
			if(strExcelName.endsWith(".csv"))
				lReadExcel = new UploadFileReader().readCsv(CommMethod.getProjectDir()+strExcelName,iFromRowNum);	
			else if(strExcelName.endsWith(".xls"))
				lReadExcel = new UploadFileReader().readXls(CommMethod.getProjectDir()+strExcelName,iFromRowNum);	
			else{
				throw new ImpException("上传文件类型错误------ImportControler.getImportMsg_drmanage();ic01");
			}
			
			hashReturn.put("xlslist",lReadExcel);
		} 
		catch (ImpException e) {
			System.out.println(e.getMessage());
		}
		
		return  hashReturn;
	}
	
	//
	public List getErrorByIsChecked(List lIsChecked){		
		List lReturn = new ArrayList();
		List lLine = null;
		for(int i=0;i<lIsChecked.size();i++)
		{
			lLine = (List) lIsChecked.get(i);
			if(!"".equals(lLine.get(lLine.size()-1)))
				lReturn.add(lLine);
		}
		return lReturn;
	}
		
	public class UploadFileReader{		
		private String trimQuart(String str){
			String strReturn = "";
			if(CommMethod.matcher("^\".*\"$",str)){
				strReturn = str.substring(1, str.length()-1);
				strReturn = strReturn.replaceAll("\"\"", "\"");
			}else{
				strReturn = str;
			}
			return strReturn;
		}
		
		/**
		 * mySplit
		 * 自定义的方法，正确解析字段中的半角逗号和双引号
		 * @param strLine
		 * @return
		 */
		
		 //解析一行数据的方法
		 private ArrayList mySplit(String strLine){
			ArrayList list1 = new ArrayList();			
			int intyh=0;			//对引号个数的记录
			String temp="";			//当前字符串取到的字符
			StringBuffer getstr = new StringBuffer();		//正确分割后，放入ArrayList的字符串
		
			for(int i=0;i<strLine.length();i++){
				temp = strLine.substring(i,i+1);			
				if(temp!=null){  				
					if(temp.equals(",")){
						if(intyh % 2 ==0){
							list1.add(trimQuart(getstr.toString().trim().replaceAll("	", "")));
							if(i==strLine.length()-1)
								list1.add("");
							getstr = new StringBuffer();
						}
						else
							getstr.append(temp);
					}else if(temp.equals("\"")){
						intyh++;
						getstr.append(temp);
						if(i == strLine.length()-1)
							list1.add(getstr.toString().trim().replaceAll("	", ""));		
					}else{
						getstr.append(temp);
						//判断当i等于字符串长度的时候，就是最后一个字符，要将最后的字符添加到list对象中，否则最后一个字段就会丢失
						if(i == strLine.length()-1)
							list1.add(getstr.toString().trim().replaceAll("	", ""));					
					}
				}
			} 	
			//System.out.println(getstr);
			return list1;
		}
		 
		public List readCsv(String csvUri,int iFromRowNum) throws ImpException{			
			List lReturn = new ArrayList();
			List lLine = null;
			BufferedReader bufferedreader = null;
			String strTemp1 = null;
			int count = 0;
			
			try {
				bufferedreader = new BufferedReader(new FileReader(csvUri));
				while ((strTemp1 = bufferedreader.readLine()) != null) {
					strTemp1 = new String(strTemp1.getBytes("ISO-8859-1"),"gbk");
					count++;
					if(count<iFromRowNum)
						continue;
					if(!CommMethod.matcher("^( *,)* *$", strTemp1)){
						lLine = mySplit(strTemp1);
						lReturn.add(lLine);
					}
				}
				bufferedreader.close();
			} catch (FileNotFoundException e) {
				throw new ImpException("读源文件异常：FileNotFoundException------ImportControler.UploadFileReader.readCsv();ic03");
			} catch (IOException e) {
				throw new ImpException("读源文件异常：IOException------ImportControler.UploadFileReader.readCsv();ic04");
			}finally{
				try {
					bufferedreader.close();
				} catch (IOException e) {
					throw new ImpException("读源文件异常：IOException------ImportControler.UploadFileReader.readCsv();ic04");
				}
			}
			
			return lReturn;
		}
		
		public List readXls(String xlsUri,int iFromRowNum) throws ImpException{
			List lReturn = new ArrayList();
			//List lLine = null;
			Map mapLine = null;
			Workbook rwb = null;
			jxl.Sheet rs =  null;
			Cell c = null;
			int colNum = 0;
			int rowNum = 0;
			String strCellValue = "";
			String strTemp = "";
			InputStream is =null;
	    	try
			{
	    		is = new FileInputStream(xlsUri);
	    		//System.out.println(xlsUri);
			}
			catch (Exception e)
			{
				throw new ImpException("读源文件异常：Exception------ImportControler.readXls();ic05");
			}
			try
			{
				rwb = Workbook.getWorkbook(is);
			}
			catch (BiffException e)
			{
				e.printStackTrace();
				throw new ImpException("创建Workbook异常：BiffException------ImportControler.readXls();ic06");
			}
			catch (IOException e)
			{
				throw new ImpException("创建Workbook异常：IOException------ImportControler.readXls();ic07");
			}
			rs =  rwb.getSheet(0); 			// 读取第一个sheet
			colNum = rs.getColumns();		// 列数
			rowNum = rs.getRows(); 			// 行数
			for(int i=0;i<rowNum;i++){
				if(i+1<iFromRowNum)
					continue;
				//lLine = new ArrayList();
				strTemp = "";
				mapLine = new HashMap();
				for(int j=0;j<colNum;j++){
					c = rs.getCell(j, i);
					strCellValue = getCellData(c);
					mapLine.put("icol"+j, strCellValue);
					//lLine.add(strCellValue);
					strTemp += strCellValue;
				}
				if(!"".equals(strTemp)){
					lReturn.add(mapLine);
				}
			}
			rwb.close();
			try {
				is.close();
			} catch (IOException e) {
				throw new ImpException("关闭资源异常：IOException------ImportControler.readXls();ic08");
			}
			return lReturn;
		}
		
		private String getCellData(Cell cell){			
			Format format = new SimpleDateFormat("yyyy-MM-dd"); 			
			DecimalFormat dformat = new DecimalFormat("#.##########");
			
			String data = cell.getContents().trim();

			if(cell.getType()==CellType.DATE){
		       DateCell dc = (DateCell)cell;
		       data = format.format(dc.getDate()); 		       
			}else if(cell.getType()==CellType.NUMBER || cell.getType()==CellType.NUMBER_FORMULA){
			   NumberCell nc = (NumberCell)cell;			  
		       data = dformat.format(nc.getValue()); 		      
			} 
			
			return data;
		}
	}
	
	public static void main(String[] args) throws IOException{
		//System.out.println("".lastIndexOf(","));
		//System.out.println(",zc".substring(",".lastIndexOf(",")));
		HashMap hashReturn = new HashMap();
		System.out.println(new ImportControler().new UploadFileReader().mySplit("2009-2-3,,\"124,000.00\",,,1020.1098,0,现金,"));
	}
}
